import { plainToInstance } from 'class-transformer';
import { IsNotEmpty, IsString, IsNumber, validateSync } from 'class-validator';

/**
 * 环境变量
 */
class EnvironmentVariables {
  @IsString()
  @IsNotEmpty()
  REDIS_HOST: string;

  @IsNotEmpty()
  @IsNumber()
  REDIS_PORT: number;

  @IsNotEmpty()
  @IsNumber()
  REDIS_DB: number;

  @IsString()
  @IsNotEmpty()
  REDIS_PASSWORD: string;

  /** swagger url地址 */
  @IsString()
  @IsNotEmpty()
  SWAGGER_API_URL: string;

  /** swagger 标题 */
  @IsString()
  @IsNotEmpty()
  SWAGGER_TITLE: string;

  /** swagger 描述 */
  @IsString()
  @IsNotEmpty()
  SWAGGER_DESCRIPTION: string;

  /** swagger 版本 */
  @IsString()
  @IsNotEmpty()
  SWAGGER_VERSION: string;
}

// 导出一个函数，用于验证环境变量
export function validateEnvironmentVariables(
  // 环境变量
  envVariables: Record<string, unknown>
) {
  // 将环境变量转换为EnvironmentVariables实例
  const validateConfig = plainToInstance(EnvironmentVariables, envVariables, {
    enableImplicitConversion: true
  });
  // 验证validateConfig，跳过未定义的属性
  const errors = validateSync(validateConfig, {
    skipUndefinedProperties: true
  });

  // 将错误信息拼接成字符串
  let errorMessage = errors
    .map((msg) => msg.constraints[Object.keys(msg.constraints)[0]])
    .join('\n');

  // 定义颜色
  const color = {
    reset: '\x1b[0m',
    bright: '\x1b[1m',
    fgRed: '\x1b[31m'
  };
  // 将错误信息设置为红色
  errorMessage = `${color.fgRed}${color.bright}${errorMessage}${color.reset}`;
  // 如果有错误，抛出错误
  if (errors.length > 0) {
    throw new Error(errorMessage);
  }
  // 返回验证后的配置
  return validateConfig;
}
